#ifndef TCP_CONNECTION_H
#define TCP_CONNECTION_H
#include <list>
#include <thread>
#include <mutex>
#include <memory>
#include <sstream>
#include <boost/asio.hpp>
#include "logger.h"

using namespace boost::asio;
using namespace boost::asio::ip;

class TcpConnection
	: public std::enable_shared_from_this<TcpConnection>
{
public:
	TcpConnection(io_service& io_server);
	~TcpConnection()
	{
		Disconnect();
	}

	void Start();
	void SendMessage(const std::string& message);
	std::string remote_addr();

	void Disconnect();

	void id(int index)
	{
		index_ = index;
	}

	int id(){	return index_;	}

	tcp::socket& socket(){ return socket_; };

private:
	void OnMessage(const boost::system::error_code& err, std::size_t bytes_transferred);
	void OnWriteFinish(const boost::system::error_code& err, std::size_t bytes_transferred);

	void PrepareRead();
	void HandleMessage(const std::string& data);

private:
	tcp::socket		    socket_;
	boost::asio::strand	    strand_;
	int			    index_;
	boost::asio::streambuf  req_stream_;
	boost::asio::streambuf  resp_stream_;
	std::mutex		    mutex_;
};

typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;

#endif
